# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/8/12
library(optparse)
library(magrittr)
library(impute)
library(tidyverse)
library(NormalizeMets)
library(FitAR)

add1 <- function(x) {

  if (any(x < 0)) {
    stop("应当在填充缺失值后再进行log转换！")
  }

   x + 1
}

option_list <- list(
  make_option("--cc", default = "calculate_config.json", type = "character", help = "config file"),
  make_option("--si", default = "1;0", type = "character", help = "step "),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

configJson <- fromJSON(opt$cc)

si <- opt$si %>%
  str_split(";") %>%
  unlist()
step <- si[1] %>%
  as.numeric()

transformMethod  <- configJson$datas$transformMethod[step]
glogMethod  <- configJson$datas$glogMethod[step]
glog  <- configJson$datas$glog[step] %>%
  as.numeric()

data <- read_tsv(str_c(step - 1, ".result.txt")) %>%
  rename(Metabolite = 1)

if (transformMethod == "log2") {
  data <- data %>%
    mutate_at(vars(-c("Metabolite")), function(x) {
      log2(add1(x))
    })
}else if (transformMethod == "ln") {
  data <- data %>%
    mutate_at(vars(-c("Metabolite")), function(x) {
      log(add1(x))
    })
}else if (transformMethod == "log10") {
  data <- data %>%
    mutate_at(vars(-c("Metabolite")), function(x) {
      log10(add1(x))
    })
}else if (transformMethod == "cube") {
  data <- data %>%
    mutate_at(vars(-c("Metabolite")), function(x) {
      x^(1 / 3)
    })
}else if (transformMethod == "glog") {
  glogV <- if (glogMethod == "custom") {
    glog
  }else {
    onlyData <- data %>%
      select(-"Metabolite")
    minValue <- min(onlyData, na.rm = T)
    minValue / 10
  }
  data <- data %>%
    mutate_at(vars(-c("Metabolite")), function(x) {
      glog(x, a = glogV)
    })

}

outData <- data
outData

write_tsv(outData, str_c(step, ".result.txt"))
write_csv(outData, str_c(step, ".transform.csv"))








